<template>
  <a-card title="碳排报告管理">
    <a-form layout="vertical">
      <a-form-item label="选择报告年度">
        <a-select v-model="selectedYear" placeholder="选择年度" style="width: 300px">
          <a-select-option v-for="i in time" :key="i" :value="i">{{ i }}</a-select-option>
        </a-select>
        <a-button type="primary" style="margin-left: 10px" html-type="submit">
          生成报告
        </a-button>
      </a-form-item>
    </a-form>

    <a-table
      :row-selection="{
        selectedRowKeys: state.selectedRowKeys,
        onChange: onSelectChange,
      }"
      :columns="columns"
      :data-source="reports"
      rowKey="emissionReportId"
      style="margin-top: 20px"
      :pagination="pagination"
      @change="handlechange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'emissionFile'"
          ><a @click="Checkpdf(record)">查看</a>
        </template>
      </template>
    </a-table>
  </a-card>

  <!-- 碳排审核页面 -->
  <a-modal :open="isAuditVisible" title="碳排审核" @ok="handleAuditConfirm">
    <p>审核报告的详细信息...</p>
  </a-modal>

  <a-modal :open="ispdf" title="报告内容" :footer="null" @cancel="handlecancel">
    <iframe :src="pdfUrl"></iframe>
  </a-modal>
</template>

<script setup>
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { repoter } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/repoter";
import { smartSentry } from "/@/lib/smart-sentry";
const availableYears = ref([2021, 2022, 2023]);
const selectedYear = ref(null);
const reports = ref([]);
const state = reactive({
  selectedRowKeys: [],
  loading: false,
});
const ispdf = ref(false);
const pdfUrl = ref(null);
const pdfContainer = ref(null);
const total = ref(null);
const time = ref("");
const columns = [
  {
    title: "id",
    dataIndex: "emissionReportId",
    key: "emissionReportId",
    align: "center",
  },
  {
    title: "碳排报告名称",
    dataIndex: "emissionReportName",
    key: "emissionReportName",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "emissionReportStatus",
    key: "emissionReportStatus",
    align: "center",
  },
  { title: "报告创建时间", dataIndex: "createTime", key: "createTime", align: "center" },
  {
    title: "碳排报告内容",
    dataIndex: "emissionFile",
    key: "emissionFile",
    align: "center",
  },
];

const queryFormState = reactive({
  pageNum: 1,
  pageSize: 10,
});

const queryForm = reactive({ ...queryFormState });

const pagination = computed(() => ({
  total: total.value,
  pageSize: queryFormState.pageSize,
  current: queryFormState.pageNum,
  showTotal: (total) => `总共${total}项`,
}));
async function queryData() {
  try {
    queryForm.pageNum = queryFormState.pageNum;
    queryForm.pageSize = queryFormState.pageSize;
    const queryResult = await repoter.query(queryForm);
    reports.value = queryResult.data.list;
    total.value = queryResult.data.total;
    const timeSet = new Set();
    queryResult.data.list.forEach((item) => {
      const year = dayjs(item.createTime).format("YYYY");
      timeSet.add(year);
    });
    time.value = Array.from(timeSet);
    console.log(time.value);
  } catch (e) {
    smartSentry.captureError(e);
  }
}
const handlechange = (pagination, filters, sorter) => {
  queryFormState.pageNum = pagination.current;
  queryFormState.pageSize = pagination.pageSize;
  queryData();
};

// 修改后的 rowSelection，绑定 selectedRowKeys 状态以确保单独选择
const onSelectChange = (selectedRowKeys, selectedRows) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys, selectedRows);
  state.selectedRowKeys = selectedRowKeys;
};

const handleGenerateReport = () => {
  const existingReport = reports.value.find(
    (report) => report.year === selectedYear.value && report.status !== "作废"
  );
  if (existingReport) {
    return alert(`当前年度有${existingReport.status}报告，请作废后重新生成`);
  }

  reports.value.push({
    year: selectedYear.value,
    status: "待审核",
    summary: "新报告生成...",
  });
};

const isAuditVisible = ref(false);

const handleStatusClick = (report) => {
  if (report.status === "待审核") {
    isAuditVisible.value = true;
  } else {
    alert(`报告状态: ${report.status}`);
  }
};

const handleAuditConfirm = () => {
  console.log("审核确认");
  isAuditVisible.value = false;
};
//查看pdf
const Checkpdf = (pdfurl) => {
  ispdf.value = true;
  pdfUrl.value = pdfurl.emissionFile;
};
const handlecancel = () => {
  ispdf.value = false;
};
onMounted(() => {
  queryData();
  if (!pdfUrl.value) {
    return;
  } else {
    const pdfViewer = new pdfjs.PDFViewer({
      container: pdfContainer.value,
    });
    pdfjs.getDocument(pdfUrl).promise.then((pdf) => {
      pdfViewer.setDocument(pdf);
    });
  }
});
</script>

<style scoped>
/* 添加样式 */
</style>
